import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/material.dart';
import 'package:github_client_flutter/models/index.dart';

import 'global.dart';

class Git {
  Git([this.context]) {
    _options = Options(extra: {"context": context});
  }

  BuildContext? context;
  late Options _options;
  static Dio dio = Dio(
    BaseOptions(
      baseUrl: "https://api.github.com/",
      // baseUrl: "http://192.168.1.38:3000/",
      headers: {
        HttpHeaders.acceptHeader: "application/vnd.github.squirrel-girl-preview,"
            "application/vnd.github.symmetra-preview+json",
      },
    ),
  );

  static void init() {
    dio.interceptors.add(Global.netCache);
    dio.options.headers[HttpHeaders.authorizationHeader] = Global.profile.token;

    if (!Global.isRelease) {
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return null;
      };
    }
  }

  Future<User> login(String login, String pwd) async {
    print("token $login $pwd");
    String basic = "Basic ${base64Encode(utf8.encode('$login:$pwd'))}";
    var r = await dio.get(
      "/user",
      options: _options.copyWith(
        headers: {
          HttpHeaders.authorizationHeader: basic,
        },
      ),
    );

    print(r.data);
    dio.options.headers[HttpHeaders.authorizationHeader] = basic;
    Global.netCache.cache.clear();
    Global.profile.token = basic;
    return User.fromJson(r.data);
  }

  Future<List<Repo>> getRepos({
    Map<String, dynamic>? queryParameters,
    refresh = false,
  }) async {
    if (refresh) {
      _options.extra!.addAll({refresh: true, "list": true});
    }
    var r = await dio.get<List>(
      "user/repos",
      queryParameters: queryParameters,
      options: _options,
    );
    return r.data!.map((e) => Repo.fromJson(e)).toList();
  }
}
